//
//  RuZhuViewController.m
//  WholesalerApp
//
//  Created by macox on 16/10/31.
//  Copyright © 2016年 macox. All rights reserved.
//

#import "RuZhuViewController.h"
#import "AddMapViewController.h"
#import "HomeModel.h"
#import "RuZhuModel.h"
#import "ExamineViewController.h"
#import "LoginNAVC.h"
#import "LoginViewController.h"
#import "SGGenerateQRCodeVC.h"
#import "SGScanningQRCodeVC.h"
#import <AVFoundation/AVFoundation.h>
@interface RuZhuViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate>
{
    NSString *_CompanyName;
    NSString *_ShopName;
    NSString *_CompanyAddress;
    NSString *_CompanyProvince;
    NSString *_CompanyCity;
    NSString *_CompanyCounty;
    NSString *_RoomNum;
    NSString *_CompanyPhone;
    NSString *_BusinessLicenceNumber;
    NSString *_BusinessProvince;
    NSString *_BusinessCity;
    NSString *_BusinessCounty;
    NSString *_legalPerson;
    NSString *_CompanyFoundingDate;
    NSString *_BusinessSphere;
    NSString *_BusinessLicenceNumberPhoto;
    NSInteger clickCount;
    UIView *bView;
    NSMutableArray *YingyeArr;
    NSString *longitude;
    NSString *latitude;
    
}
@property (weak, nonatomic) IBOutlet UIImageView *PhotoImageV;
@property (nonatomic,strong)UITableView *classTableView;
@property (nonatomic ,strong)UITableView *ruZhuTableView;    //主tableView
@property (nonatomic ,strong)NSMutableArray *leftLabelAry;
@property (nonatomic ,strong)NSMutableArray *placeholdAry;
@property (nonatomic ,strong)NSMutableArray *datas;
@property (nonatomic,strong)UIImageView *licenseImage;
@property (nonatomic , strong) NSMutableArray *ChanelDataArray;
@property (weak, nonatomic) IBOutlet UITextField *CompanyTextFiled;//公司名称
@property (weak, nonatomic) IBOutlet UITextField *StoreNameTextFiled;//商铺名称

@property (weak, nonatomic) IBOutlet UITextField *MenNum;//门牌号
@property (weak, nonatomic) IBOutlet UITextField *PhoneTextFiled;//电话
@property (weak, nonatomic) IBOutlet UITextField *YinYeTexyField;//营业执照号
@property (weak, nonatomic) IBOutlet UITextField *LeaglTextFiled;//法人
@property (weak, nonatomic) IBOutlet UITextField *StateDateTextFiled;//成立日期
@property (weak, nonatomic) IBOutlet UITextField *JingYingTextFiled;//经营范围
@property (weak, nonatomic) IBOutlet UIScrollView *RuZhuScrollView;
@property (weak, nonatomic) IBOutlet UILabel *CompanyAddressLabel;//公司地址
@property (weak, nonatomic) IBOutlet UILabel *YingYeLabel;//营业执照地址
@property (nonatomic ,strong)NSNumber *Id;



@end

@implementation RuZhuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self requesteData];
    YingyeArr = [NSMutableArray array];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    title.text = @"入驻申请";
    title.backgroundColor = [UIColor clearColor];
    title.textColor = [UIColor whiteColor];
    //    title.font = [UIFont systemFontOfSize:17];
    title.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = title;
    //     [self.navigationController.navigationBar setti];
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    UIImage *classBackImage = [UIImage imageNamed:@"zuojiantou@3x-1"];
    classBackImage = [classBackImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:classBackImage style:UIBarButtonItemStylePlain target:self action:@selector(classBackAction)];
    // Do any additional setup after loading the view from its nib.
    
    
    _CompanyTextFiled.delegate = self;//公司名称
    _StoreNameTextFiled.delegate = self;//商铺名称
    
    _MenNum.delegate = self;//门牌号
    _PhoneTextFiled.delegate = self;//电话
    _YinYeTexyField.delegate = self;//营业执照号
    _LeaglTextFiled.delegate = self;//法人
    _StateDateTextFiled.delegate = self;//成立日期
    _JingYingTextFiled.delegate = self;//经营范围
}
#pragma mark - VC将要出现
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    //    [self.navigationController setNavigationBarHidden:NO animated:animated];
    self.navigationController.navigationBarHidden = NO;
    //获取通知中心单例对象
    //    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}
#pragma mark -- 返回
- (void)classBackAction{
    _PhotoImageV.image = [UIImage imageWithData:[NNSingleton sharedSingleton].imageData];
    LoginViewController *loginView = [[LoginViewController alloc]init];
    LoginNAVC *naVC = [[LoginNAVC alloc] initWithRootViewController:loginView];
    self.view.window.rootViewController = naVC;
    //    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- 设置提交按钮

- (IBAction)TiJiaoBtnAction:(UIButton *)sender {
    
    [self tijiaoBtnClick];
}
- (IBAction)AddRessBtn:(UIButton *)sender {
    NSLog(@"地址");
    AddMapViewController *vc = [[AddMapViewController alloc] init];
    vc.addressBlock = ^(NSDictionary *dic) {
        _CompanyAddress = [NSString stringWithFormat:@"%@",[dic objectForKey:@"address"]];// 一串地址
        _CompanyAddressLabel.text = _CompanyAddress;
        _CompanyProvince = [NSString stringWithFormat:@"%@",[dic objectForKey:@"province"]];// 省份名称
        NSLog(@"+++++++++++____+________%@",_CompanyProvince);
        _CompanyCity = [NSString stringWithFormat:@"%@",[dic objectForKey:@"city"]];// 城市名称
        NSLog(@"++++++++++++________%@",_CompanyCity);
        _CompanyCounty = [NSString stringWithFormat:@"%@",[dic objectForKey:@"district"]];// 区县名称
        NSLog(@"++++++++++++________%@",_CompanyCounty);
        
        longitude = [NSString stringWithFormat:@"%@",[dic objectForKey:@"lon"]];// 经度
        latitude = [NSString stringWithFormat:@"%@",[dic objectForKey:@"lat"]];// 纬度
        
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)ClassCity:(UIButton *)sender {
    [self selectCity];
}
#pragma mark -- 省市区选择
- (void)selectCity{
    clickCount = 0;
    bView = [[UIView alloc]initWithFrame:CGRectMake(0, kScrernHeight - 500, kScrernWidth, 300)];
    bView.backgroundColor = [UIColor colorWithHue:0.21 saturation:1.00 brightness:0.69 alpha:1.00];
    [self.view addSubview:bView];
    
    _classTableView =[[UITableView alloc]initWithFrame:CGRectMake(0,20, kScrernWidth,300) style:UITableViewStylePlain];
    _classTableView.showsVerticalScrollIndicator = FALSE;
    _classTableView.delegate=self;
    _classTableView.dataSource=self;
    _classTableView.tag = 10000003;
    //    _classTableView.backgroundColor = [UIColor redColor];
    //    _classTableView.tableFooterView = [[UIView alloc] init];
    [bView addSubview:_classTableView];
    [self commodityProiceDataRequest];
    
}
#pragma mark -- 省值
- (void)commodityProiceDataRequest{
    _ChanelDataArray = [NSMutableArray array];
    NSDictionary *param = @{@"ParentId":@"0"};
    [GDJHttpTool get:GetAreasByPId params:param success:^(id responseObj) {
        NSLog(@"=======%@", responseObj);
        NSLog(@"%@", param);
        if ([[responseObj objectForKey:@"Err"] intValue]) {
            
        }else{
            
            
            _ChanelDataArray =   [HomeModel mj_objectArrayWithKeyValuesArray:[responseObj objectForKey:@"Areas"]];
            NSLog(@"+++++++++++%lu", (unsigned long)_ChanelDataArray.count)  ;
            
        }
        [_classTableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
#pragma mark -- 市值
- (void)commodityCountyDataRequest:(NSString *)CountyID{
    //    _ChanelDataArray = [NSMutableArray array];
    NSDictionary *param = @{@"ParentId":CountyID};
    [GDJHttpTool get:GetAreasByPId params:param success:^(id responseObj) {
        NSLog(@"=======%@", responseObj);
        NSLog(@"%@", param);
        if ([[responseObj objectForKey:@"Err"] intValue]) {
            
        }else{
            
            [_ChanelDataArray removeAllObjects];
            _ChanelDataArray =   [HomeModel mj_objectArrayWithKeyValuesArray:[responseObj objectForKey:@"Areas"]];
            NSLog(@"+++++++++++%lu", (unsigned long)_ChanelDataArray.count)  ;
            
        }
        [_classTableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}
#pragma mark -- 提交按钮点击方法
- (void)tijiaoBtnClick{
    
    
    
    
    
    
    if (!_CompanyTextFiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"公司名不能为空" ];
    }else if(!_StoreNameTextFiled.text.length){
        [SVProgressHUD showErrorWithStatus:@"商铺名不能为空" ];
        
    }else if(_StoreNameTextFiled.text.length<4){
        [SVProgressHUD showErrorWithStatus:@"商铺名长度大于4个汉字" ];
        
    }
    else if(!_CompanyProvince.length){
        [SVProgressHUD showErrorWithStatus:@"公司地址不能为空" ];
        
    }else if (!_CompanyCity.length){
        [SVProgressHUD showErrorWithStatus:@"公司地址不能为空" ];
        
    }else if (!_MenNum.text.length){
        [SVProgressHUD showErrorWithStatus:@"门牌号不能为空" ];
        
        
    }else if (!_PhoneTextFiled.text.length){
        [SVProgressHUD showErrorWithStatus:@"电话不能为空" ];
        
        
    }else if (!_YinYeTexyField.text.length){
        [SVProgressHUD showErrorWithStatus:@"公司营业执照号不能空" ];
        
        
        
    }else if (!_LeaglTextFiled.text.length){
        [SVProgressHUD showErrorWithStatus:@"法人不能为空" ];
        
        
    }else if (!_StateDateTextFiled.text.length){
        [SVProgressHUD showErrorWithStatus:@"成立日期不能为空" ];
        
        
    }else if (!_JingYingTextFiled.text.length){
        [SVProgressHUD showErrorWithStatus:@"经营范围不能为空" ];
        
        
    }else if (!_BusinessLicenceNumberPhoto.length){
        [SVProgressHUD showErrorWithStatus:@"图片不能为空" ];
        
        
    }else{
        RuZhuModel *model = [[RuZhuModel alloc]init];
        model.ShouJiHao = GETPHONE;
        model.Token = GETTOKEN;
        model.Duuid = GETUUID;
        NSLog(@"======-----%@",_CompanyName);
        model.CompanyAddress = _CompanyAddress;
        model.CompanyName = _CompanyTextFiled.text;
        model.ShopName = _StoreNameTextFiled.text;
        model.CompanyProvince = _CompanyProvince;
        model.CompanyCity = _CompanyCity;
        model.CompanyCounty = _CompanyCounty;
        model.RoomNum = _MenNum.text;
        model.CompanyPhone = _PhoneTextFiled.text;
        model.BusinessLicenceNumber = _YinYeTexyField.text;
        if (YingyeArr.count != 0) {
            model.BusinessProvince = YingyeArr[YingyeArr.count - 3];
            model.BusinessCity = YingyeArr[YingyeArr.count -2];
            model.BusinessCounty = YingyeArr[YingyeArr.count -1];
        }else{
            model.BusinessProvince = _BusinessProvince;
            model.BusinessCity = _BusinessCity;
            model.BusinessCounty = _BusinessCounty;
        }
        
        model.legalPerson = _LeaglTextFiled.text;
        model.CompanyFoundingDate = _StateDateTextFiled.text;
        model.BusinessSphere = _JingYingTextFiled.text;
        model.Photo = _BusinessLicenceNumberPhoto;
        model.Lng = longitude;
        model.Lat = latitude;
        model.Id  =_Id;
        [self.datas addObject:model];
        
        
        
        [GDJHttpTool post:ShopSave params:model.mj_keyValues success:^(id responseObj) {
            
            NSLog(@"======%@",model.mj_keyValues);
            NSLog(@"%@",responseObj);
            if ([[responseObj objectForKey:@"Err"] intValue] == 0) {
                //            UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                //            //获取Main.storyboard中的首页
                //          RootViewController   *rootVC = [mainStory instantiateViewControllerWithIdentifier:@"mainVC"];
                //            self.view.window.rootViewController = rootVC;
                ExamineViewController *exminVC = [[ExamineViewController alloc]init];
                [self.navigationController pushViewController:exminVC animated:YES];
            }else{
                //              [SVProgressHUD  showWithStatus:[responseObj objectForKey:@"ErrMsg"]];
            }
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        }];
        
    }
    
    
    
    
    
}
- (void)requesteData{
    
    NSDictionary *param = @{@"ShouJiHao":GETPHONE,@"Duuid":GETUUID,@"Token":GETTOKEN};
    NSLog(@"===----%@",param);
    [GDJHttpTool get:ShopEdit params:param success:^(id responseObj) {
        
        //        NSLog(@"======%@",model.mj_keyValues);
        NSLog(@"====13123%@",responseObj);
        if ([[responseObj objectForKey:@"Err"] intValue]) {
            
        }else{
            
            NSDictionary *dataArr = [responseObj objectForKey:@"ShopInfo"];
            RuZhuModel *model = [RuZhuModel mj_objectWithKeyValues:dataArr];
            _CompanyAddress =  model.CompanyAddress;
            _CompanyTextFiled.text = model.CompanyName;//公司名称
            _StoreNameTextFiled.text = model.ShopName;//商铺名称
            _CompanyAddressLabel.text =  model.CompanyAddress;
            
            _CompanyProvince = model.CompanyProvince;
            _CompanyCity = model.CompanyCity;
            _CompanyCounty = model.CompanyCounty;
            _MenNum.text =  model.RoomNum;//门牌号
            _PhoneTextFiled.text =  model.CompanyPhone;//电话
            _YinYeTexyField.text =  model.BusinessLicenceNumber;//营业执照号
            _LeaglTextFiled.text =  model.legalPerson;//法人
            _StateDateTextFiled.text =  model.CompanyFoundingDate;//成立日期
            _JingYingTextFiled.text =  model.BusinessSphere;//经营范围
            _BusinessProvince = model.BusinessProvince;
            _BusinessCounty = model.BusinessCounty;
            _BusinessCity = model.BusinessCity;
            
            _YingYeLabel.text = [NSString stringWithFormat:@"%@%@%@",model.BusinessProvince,model.BusinessCounty,model.BusinessCity];
            //            PhotoImageV.image = []
            NSString *imageStr = [NSString stringWithFormat:@"%@%@",ReleaseORDebug,model.BusinessLicenceNumberPhoto];
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageStr]];
            [_PhotoImageV setImage:[UIImage imageWithData:data]];
            _Id = model.Id;
            NSString * strOne = [data base64EncodedStringWithOptions:kNilOptions];
            //            NSData *data [image base64EncodedDataWithOptions:data];
            _BusinessLicenceNumberPhoto = strOne;
            longitude = model.Lng ;
            latitude  = model.Lat;
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    //
}

#pragma mark -- tableView数据源代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _ChanelDataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (_classTableView == tableView) {
        return 1;
    } else{
        return self.leftLabelAry.count;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1 && indexPath.row == 7) {
        return 120;
    }
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"++++++-____+++*****__+++++%lu", (unsigned long)_ChanelDataArray.count)  ;
    
    static NSString *identifer=@"Mycell";
    NSLog(@"黄黄黄");
    UITableViewCell *MyCell=[tableView cellForRowAtIndexPath:indexPath];
    if (MyCell==nil) {
        MyCell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    
    MyCell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSLog(@"黄+%lu", (unsigned long)_ChanelDataArray.count)  ;
    
    if (_ChanelDataArray .count== 0) {
        
    }else{
        NSLog(@"那你男男女女  %@",[_ChanelDataArray objectAtIndex:0]);
        NSLog(@"0000  那你男男女女  %lu",(unsigned long)_ChanelDataArray.count);
        HomeModel *model= [_ChanelDataArray objectAtIndex:indexPath.row];
        MyCell.textLabel.textColor = [UIColor colorWithRed:0.35 green:0.35 blue:0.35 alpha:1.00];
        MyCell.textLabel.text = model.Name;
    }
    
    NSLog(@"====------%lu",(unsigned long)YingyeArr.count);
    if (YingyeArr.count  % 3 == 0 &&  YingyeArr.count != 0 ) {
        NSString *sting = [NSString stringWithFormat:@"%@%@%@",YingyeArr[YingyeArr.count - 3],YingyeArr[YingyeArr.count - 2],YingyeArr[YingyeArr.count -1]];
        _YingYeLabel.text = sting;
        NSLog(@"===你好%@",sting);
    }
    return MyCell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    clickCount++;
    
    NSLog(@"那你男男女女  %@",[_ChanelDataArray objectAtIndex:0]);
    NSLog(@"0000  那你男男女女  %lu",(unsigned long)_ChanelDataArray.count);
    HomeModel *model= [_ChanelDataArray objectAtIndex:indexPath.row];
    NSString *proiceV= model.Name;
    [YingyeArr addObject:proiceV];
    
    [self commodityCountyDataRequest:[NSString stringWithFormat:@"%d",model.Id]];
    
    if (clickCount == 3) {
        bView.hidden = YES;
        NSLog(@"黄黄黄❤️%lu",(unsigned long)YingyeArr.count);
        
        [_classTableView reloadData];
    }
    
}

#pragma mark -- 营业执照照片
- (IBAction)YinYePhoto:(UIButton *)sender {
    [self selectPictureUploadMode];
}
#pragma mark -- 选择图片上传方式
- (void)selectPictureUploadMode{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"选择照片" message:@"从相册选取照片或拍照发送" preferredStyle:UIAlertControllerStyleActionSheet];
    
    // 1、 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        [alert addAction:[UIAlertAction actionWithTitle:@"相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
            imagePickController.delegate = self;
            imagePickController.allowsEditing = YES;
            imagePickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickController animated:YES completion:^{
            }];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
            imagePickController.delegate = self;
            imagePickController.allowsEditing = YES;
            imagePickController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickController animated:YES completion:^{
            }];
        }]];
        
    } else {
        [alert addAction:[UIAlertAction actionWithTitle:@"相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init];
            imagePickController.delegate = self;
            imagePickController.allowsEditing = YES;
            imagePickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickController animated:YES completion:^{
            }];
        }]];
    }
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alert dismissViewControllerAnimated:YES completion:nil];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self verifyIdentifier:image];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark -- 上传店铺图片
-(void)verifyIdentifier:(UIImage *)image {
    
    NSData *dataPostOne = [self resetSizeOfImageData:image maxSize:1024];
    
    NSString * strOne = [dataPostOne base64EncodedStringWithOptions:kNilOptions];
    //    NSLog(@" 不要不快乐  %lu",(unsigned long)_imageArray.count);
    _BusinessLicenceNumberPhoto = strOne;
    _PhotoImageV.image = [UIImage imageWithData:dataPostOne];
    _PhotoImageV.backgroundColor = [UIColor greenColor];
    //    _PhotoImageV.frame = CGRectMake(self.view.center.x -75, 10,150, 100);
    [NNSingleton sharedSingleton].imageData = dataPostOne;
    //    [_ruZhuTableView reloadData];
    
}
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName {
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1.f);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}

- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize{
    //先调整分辨率
    CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
    
    CGFloat tempHeight = newSize.height / 1024;
    CGFloat tempWidth = newSize.width / 1024;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
    } else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
    }
    UIGraphicsBeginImageContext(newSize);
    [source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //调整大小
    NSData *imageData = UIImageJPEGRepresentation(newImage, 1.0);
    NSUInteger sizeOrigin = [imageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    if (sizeOriginKB > maxSize) {
        NSData *finallImageData = UIImageJPEGRepresentation(newImage,0.3);
        return finallImageData;
    }
    return imageData;
}


#pragma mark --- textField代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) {
        [self.view endEditing:YES];
    }
    return YES;
}
- (void)keyboardWillShow:(NSNotification *)notification {
    /*
     Reduce the size of the text view so that it's not obscured by the keyboard.
     Animate the resize so that it's in sync with the appearance of the keyboard.
     */
    NSDictionary *userInfo = [notification userInfo];
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGRect tableViewFrame = self.view.bounds;
    tableViewFrame.size.height = keyboardTop - self.view.bounds.origin.y;
    
    // Get the duration of the animation.
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    // Animate the resize of the text view's frame in sync with the keyboard's appearance.
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    
    _RuZhuScrollView.frame = CGRectMake(0,0, kScrernWidth,keyboardTop );
    [UIView commitAnimations];
}
- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    /*
     Restore the size of the text view (fill self's view).
     Animate the resize so that it's in sync with the disappearance of the keyboard.
     */
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    _RuZhuScrollView.frame= CGRectMake(0,0, kScrernWidth,kScrernHeight);
    [UIView commitAnimations];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
